<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>机房纪律管理系统</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            text-align: center;
        }
        h1 {
            margin-bottom: 10px;
        }
        .subtitle {
            opacity: 0.8;
            font-size: 14px;
        }
        .tab-container {
            display: flex;
            background: #34495e;
        }
        .tab {
            padding: 15px 20px;
            color: white;
            cursor: pointer;
            transition: background 0.3s;
        }
        .tab.active {
            background: #2c3e50;
            border-bottom: 3px solid #3498db;
        }
        .tab-content {
            display: none;
            padding: 20px;
        }
        .tab-content.active {
            display: block;
        }
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        .card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #3498db;
        }
        .card h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .card h3 i {
            color: #3498db;
        }
        .class-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .class-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            position: relative;
        }
        .class-card.safe {
            border-left-color: #2ecc71;
        }
        .class-card.warning {
            border-left-color: #f39c12;
        }
        .class-card.danger {
            border-left-color: #e74c3c;
        }
        .class-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .class-name {
            font-weight: bold;
            font-size: 18px;
            color: #2c3e50;
        }
        .class-score {
            font-size: 24px;
            font-weight: bold;
            color: #3498db;
        }
        .stars {
            display: flex;
            gap: 5px;
            margin: 10px 0;
        }
        .star {
            color: #f39c12;
            font-size: 20px;
        }
        .empty-star {
            color: #ddd;
            font-size: 20px;
        }
        .status {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
            margin-top: 10px;
            display: inline-block;
        }
        .status.frozen {
            background: #e74c3c;
            color: white;
        }
        .status.good {
            background: #27ae60;
            color: white;
        }
        .violation-form, .class-form {
            display: grid;
            gap: 10px;
            margin-top: 15px;
        }
        select, input, button, textarea {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        button {
            background: #3498db;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #2980b9;
        }
        button.danger {
            background: #e74c3c;
        }
        button.danger:hover {
            background: #c0392b;
        }
        button.success {
            background: #27ae60;
        }
        button.success:hover {
            background: #219a52;
        }
        button.warning {
            background: #f39c12;
        }
        button.warning:hover {
            background: #e67e22;
        }
        .history {
            margin-top: 20px;
            max-height: 300px;
            overflow-y: auto;
        }
        .history-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            font-size: 12px;
        }
        .history-item.negative {
            border-left: 3px solid #e74c3c;
            background: #ffeaea;
        }
        .history-item.positive {
            border-left: 3px solid #27ae60;
            background: #eaffea;
        }
        .threshold-setter {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 10px;
        }
        .threshold-setter input {
            width: 80px;
        }
        .class-list {
            margin-top: 15px;
        }
        .class-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .class-actions {
            display: flex;
            gap: 5px;
        }
        .class-item button {
            padding: 5px 10px;
            font-size: 12px;
        }
        .quick-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 15px;
        }
        .quick-action-btn {
            padding: 15px;
            text-align: center;
            background: #ecf0f1;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .quick-action-btn:hover {
            background: #d5dbdb;
            transform: translateY(-2px);
        }
        .current-class {
            background: #e8f4fd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            text-align: center;
            font-weight: bold;
            font-size: 18px;
        }
        .empty-state {
            text-align: center;
            padding: 30px;
            color: #7f8c8d;
        }
        .delete-class-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: transparent;
            color: #95a5a6;
            border: none;
            font-size: 16px;
            padding: 5px;
        }
        .delete-class-btn:hover {
            color: #e74c3c;
        }
        .data-management {
            margin-top: 20px;
            padding: 15px;
            background: #e8f4fd;
            border-radius: 8px;
        }
        .data-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 10px;
        }
        .import-area {
            margin-top: 15px;
            padding: 10px;
            border: 2px dashed #3498db;
            border-radius: 5px;
            text-align: center;
        }
        .file-input {
            display: none;
        }
        .file-label {
            display: inline-block;
            padding: 10px 15px;
            background: #3498db;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        .server-status {
            position: fixed;
            top: 10px;
            right: 10px;
            background: #27ae60;
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            z-index: 1000;
        }
        
        /* 新增的CSS样式 */
        .class-controls {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 15px;
        }
        
        .timer-display {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            margin: 10px 0;
            color: #2c3e50;
        }
        
        .timer-controls {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        
        .session-info {
            background: #e8f4fd;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            font-size: 14px;
        }
        
        .free-time-badge {
            display: inline-block;
            background: #27ae60;
            color: white;
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 12px;
            margin-left: 10px;
        }
        
        .attendance-status {
            display: flex;
            align-items: center;
            margin-top: 10px;
            font-size: 13px;
        }
        
        .attendance-dots {
            display: flex;
            margin-left: 10px;
        }
        
        .attendance-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin: 0 2px;
            background: #ddd;
        }
        
        .attendance-dot.active {
            background: #27ae60;
        }
        
        .attendance-dot.inactive {
            background: #e74c3c;
        }
        
        /* 增强版进度条样式 */
        .progress-container {
            margin: 20px 0;
            position: relative;
        }
        
        .progress-labels {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        
        .progress-bar {
            height: 30px; /* 增加高度以容纳规则标签 */
            background: linear-gradient(to right, 
                #e74c3c 0%, #e74c3c 20%,
                #f39c12 20%, #f39c12 40%,
                #f1c40f 40%, #f1c40f 60%,
                #2ecc71 60%, #2ecc71 80%,
                #27ae60 80%, #27ae60 100%);
            border-radius: 15px;
            position: relative;
            overflow: hidden;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.2);
        }
        
        .progress-fill {
            height: 100%;
            background-color: rgba(255, 255, 255, 0.7);
            border-radius: 15px;
            position: relative;
            transition: width 0.5s ease;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        .progress-indicator {
            position: absolute;
            right: -15px;
            top: 50%;
            transform: translateY(-50%);
            background: #2c3e50;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 12px;
            white-space: nowrap;
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        
        .rule-markers {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
        }
        
        .rule-marker {
            position: absolute;
            top: 0;
            height: 100%;
            width: 2px;
            background: rgba(255, 255, 255, 0.7);
        }
        
        .rule-label {
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            white-space: nowrap;
            background: rgba(255, 255, 255, 0.9);
            padding: 2px 6px;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
            font-weight: bold;
        }
        
        .rule-label.penalty {
            color: #c0392b;
        }
        
        .rule-label.reward {
            color: #27ae60;
        }
        
        .zone-labels {
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
            font-size: 11px;
            font-weight: bold;
        }
        
        .zone-label {
            text-align: center;
            padding: 2px 5px;
            border-radius: 5px;
            color: white;
            flex: 1;
            margin: 0 2px;
        }
        
        .zone-0 { background: #e74c3c; }
        .zone-1 { background: #f39c12; }
        .zone-2 { background: #f1c40f; color: #2c3e50; }
        .zone-3 { background: #2ecc71; }
        .zone-4 { background: #27ae60; }
        
        /* 规则详情面板 */
        .rules-panel {
            margin-top: 25px;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            border-left: 4px solid #3498db;
            grid-column: 1 / -1;
        }
        
        .rules-panel h4 {
            margin-bottom: 10px;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .rules-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .rules-column h5 {
            margin-bottom: 8px;
            color: #34495e;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .rule-item {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
            background: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .rule-score {
            font-weight: bold;
            margin-right: 5px;
        }
        
        .rule-desc {
            font-size: 13px;
        }
        
        .penalty-rule .rule-score {
            color: #e74c3c;
        }
        
        .reward-rule .rule-score {
            color: #27ae60;
        }
        
        .status-details {
            margin: 10px 0;
        }

        .status-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            font-size: 13px;
        }

        .status-icon {
            margin-right: 8px;
            font-size: 16px;
        }
        
        /* 核销功能样式 */
        .clearance-panel {
            margin-top: 20px;
            background: #e8f4fd;
            border-radius: 10px;
            padding: 15px;
            border-left: 4px solid #3498db;
        }
        
        .clearance-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .clearance-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .clearance-section {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .clearance-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .clearance-info {
            display: flex;
            flex-direction: column;
        }
        
        .clearance-title {
            font-weight: bold;
            font-size: 14px;
        }
        
        .clearance-desc {
            font-size: 12px;
            color: #7f8c8d;
        }
        
        .clearance-count {
            font-size: 18px;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .clearance-count.reward {
            color: #27ae60;
        }
        
        .clearance-count.penalty {
            color: #e74c3c;
        }
        
        .clearance-actions {
            display: flex;
            gap: 5px;
        }
        
        .clearance-btn {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .rules-grid {
                grid-template-columns: 1fr;
            }
            
            .rule-label {
                font-size: 9px;
                top: -20px;
            }
            
            .zone-labels {
                font-size: 9px;
            }
            
            .class-controls {
                grid-template-columns: 1fr;
            }
            
            .clearance-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="server-status">服务器连接正常</div>
    
    <div class="container">
        <header>
            <h1>🏆 机房纪律管理系统</h1>
            <div class="subtitle">自律收获自由！</div>
        </header>
        
        <div class="tab-container">
            <div class="tab active" onclick="switchTab('record')">课堂记录</div>
            <div class="tab" onclick="switchTab('manage')">班级管理</div>
            <div class="tab" onclick="switchTab('history')">历史记录</div>
            <div class="tab" onclick="switchTab('data')">数据管理</div>
        </div>
        
        <!-- 课堂记录标签页 -->
        <div id="record" class="tab-content active">
            <div class="current-class" id="currentClassDisplay">
                请先选择或创建一个班级
            </div>
            
            <!-- 上课控制面板 -->
            <div class="card">
                <h3>⏰ 上课计时与控制</h3>
                <div class="class-selector">
                    <label>选择班级：</label>
                    <select id="classSelect" onchange="updateCurrentClass()">
                        <option value="">-- 请选择班级 --</option>
                    </select>
                </div>
                
                <div class="class-controls">
                    <div>
                        <label>课程时长（分钟）：</label>
                        <input type="number" id="classDuration" value="40" min="10" max="60">
                    </div>
                    <div class="timer-controls">
                        <button class="success" id="startClassBtn" onclick="startClass()">开始上课</button>
                        <button class="danger" id="endClassBtn" onclick="endClass()" disabled>结束上课</button>
                    </div>
                </div>
                
                <div class="timer-display" id="timerDisplay">
                    40:00
                </div>
                
                <div class="session-info" id="sessionInfo">
                    当前没有进行中的课程
                </div>
            </div>
            
            <div class="card">
                <h3>📊 当前班级纪律状态</h3>  <!-- 修改标题 -->
                <div class="threshold-setter">
                    <label>特权冻结阈值：</label>
                    <input type="number" id="freezeThreshold" value="30" min="0">
                    <button onclick="updateThreshold()">更新</button>
                </div>
                <div class="class-grid" id="classGrid">
                    <!-- 班级卡片将通过JavaScript动态生成，现在只显示当前选中班级 -->
                </div>
            </div>
                
                <div class="card">
                    <h3>✏️ 快速记录操作</h3>
                    
                    <div class="quick-actions">
                        <div class="quick-action-btn" onclick="quickRecord(-1)">
                            <div>🚶 <b>轻微违纪</b>：随意走动、小声聊天</div>
                            <div>-1分</div>
                        </div>
                        <div class="quick-action-btn" onclick="quickRecord(-2)">
                            <div>🎮 <b>私自游玩</b>：玩游戏、浏览无关内容、逃避任务</div>
                            <div>-2分</div>
                        </div>
                        <div class="quick-action-btn" onclick="quickRecord(-3)">
                            <div>⚠️ <b>严重违纪</b>：顶撞教师、恶意破坏、大声喧哗</div>
                            <div>-3分</div>
                        </div>
                        <div class="quick-action-btn" onclick="quickRecord(1)">
                            <div>⭐ <b>良好表现</b>：积极发言、帮助同学、纪律优良</div>
                            <div>+1分</div>
                        </div>
                        <div class="quick-action-btn" onclick="quickRecord(2)">
                            <div>🌟 <b>优秀表现</b>：主动探究、协作精神、完成任务</div>
                            <div>+2分</div>
                        </div>
                        <div class="quick-action-btn" onclick="quickRecord(3)">
                            <div>🏅 <b>突出贡献</b>：集体合作、示范引领、创新应用</div>
                            <div>+3分</div>
                        </div>
                    </div>
                    
                    <div class="violation-form">
                        <label>自定义记录：</label>
                        <input type="number" id="customPoints" placeholder="输入分数（正负均可）">
                        <textarea id="customReason" placeholder="记录原因..."></textarea>
                        <button onclick="customRecord()">记录</button>
                    </div>
                </div>
                
                <!-- 核销功能面板 -->
                <!-- 替换原有的核销面板部分 -->
                 <div class="clearance-panel">
                    <div class="clearance-header">
                        <h3>📋 奖励与惩罚执行</h3>
                        <button class="warning" onclick="resetAllClearances()" id="resetClearanceBtn" disabled>重置分数</button>
                    </div>
                    <div class="clearance-content">
                        <div class="clearance-section">
                            <h4>🎁 自由探索时间</h4>
                            <div id="rewardClearances">
                                <div class="clearance-item">
                                    <div class="clearance-info">
                                        <div class="clearance-title">可用自由探索时间</div>
                                        <div class="clearance-desc" id="rewardDesc">加载中...</div>
                                    </div>
                                    <div class="clearance-actions">
                                        <span class="clearance-count reward" id="rewardCount">0</span>
                                        <div class="clearance-controls">
                                            <input type="number" id="rewardMinutes" value="5" min="1" max="15" style="width: 60px;">
                                            <button class="clearance-btn success" onclick="useRewardTime()">使用时间</button>
                                        </div>
                                    </div>
                                </div>
                                <!-- 移除了计时器控件 -->
                            </div>
                        </div>
                        <div class="clearance-section">
                            <h4>⚠️ 待执行惩罚</h4>
                            <div id="penaltyClearances">
                                <div class="clearance-item">
                                    <div class="clearance-info">
                                        <div class="clearance-title">待执行停课节数</div>
                                        <div class="clearance-desc" id="penaltyDesc">加载中...</div>
                                    </div>
                                    <div class="clearance-actions">
                                        <span class="clearance-count penalty" id="penaltyCount">0</span>
                                        <div class="clearance-controls">
                                            <input type="number" id="penaltySessions" value="1" min="1" max="3" style="width: 60px;">
                                            <button class="clearance-btn danger" onclick="usePenaltySession()">执行惩罚</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 规则详情面板 -->
                <div class="rules-panel">
                    <h4>📋 奖励与惩罚规则详情</h4>
                    <div class="rules-grid">
                        <div class="rules-column">
                            <h5>⚠️ 惩罚规则</h5>
                            <div class="rule-item penalty-rule">
                                <span class="rule-score">0-20分:</span>
                                <span class="rule-desc">暂停3节机房课 + 德育处备案</span>
                            </div>
                            <div class="rule-item penalty-rule">
                                <span class="rule-score">20-30分:</span>
                                <span class="rule-desc">暂停2节机房课 + 反思谈心</span>
                            </div>
                            <div class="rule-item penalty-rule">
                                <span class="rule-score">30-40分:</span>
                                <span class="rule-desc">暂停1节机房课 + 静坐反思</span>
                            </div>
                            <div class="rule-item penalty-rule">
                                <span class="rule-score">40-50分:</span>
                                <span class="rule-desc">警告通知班主任</span>
                            </div>
                        </div>
                        <div class="rules-column">
                            <h5>🎁 奖励规则</h5>
                            <div class="rule-item reward-rule">
                                <span class="rule-score">60-70分:</span>
                                <span class="rule-desc">5分钟自由探索时间</span>
                            </div>
                            <div class="rule-item reward-rule">
                                <span class="rule-score">70-80分:</span>
                                <span class="rule-desc">8分钟自由探索时间</span>
                            </div>
                            <div class="rule-item reward-rule">
                                <span class="rule-score">80-90分:</span>
                                <span class="rule-desc">10分钟自由探索时间</span>
                            </div>
                            <div class="rule-item reward-rule">
                                <span class="rule-score">90-100分:</span>
                                <span class="rule-desc">15分钟自由探索时间</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 班级管理标签页 -->
        <div id="manage" class="tab-content">
            <div class="card">
                <h3>👥 班级管理</h3>
                <div class="class-form">
                    <input type="text" id="newClassName" placeholder="输入班级名称（如：初一1班）">
                    <input type="number" id="newClassScore" placeholder="初始分数（默认55）" value="55">
                    <button class="success" onclick="addClass()">添加新班级</button>
                </div>
                
                <div class="class-list" id="classList">
                    <!-- 班级列表将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
        
        <!-- 历史记录标签页 -->
        <div id="history" class="tab-content">
            <div class="card">
                <h3>📜 详细历史记录</h3>
                <div class="history-filter">
                    <label>筛选班级：</label>
                    <select id="historyClassFilter" onchange="filterHistory()">
                        <option value="all">所有班级</option>
                        <!-- 班级选项将通过JavaScript动态生成 -->
                    </select>
                </div>
                <div class="history" id="detailedHistory">
                    <!-- 详细历史记录将通过JavaScript动态生成 -->
                </div>
                <button class="warning" onclick="clearHistory()" style="margin-top: 15px;">清除历史记录</button>
            </div>
        </div>
        
        <!-- 数据管理标签页 -->
        <div id="data" class="tab-content">
            <div class="card">
                <h3>💾 数据备份与恢复</h3>
                
                <div class="data-management">
                    <h4>数据导出</h4>
                    <p>将当前所有数据导出为JSON文件，可用于备份或在不同设备间迁移数据。</p>
                    <div class="data-buttons">
                        <button class="success" onclick="exportData()">导出所有数据</button>
                    </div>
                    
                    <div class="import-area">
                        <h4>数据导入</h4>
                        <p>选择之前导出的JSON文件来恢复数据。<strong>注意：这将覆盖当前所有数据！</strong></p>
                        <input type="file" id="fileInput" class="file-input" accept=".json">
                        <label for="fileInput" class="file-label" onclick="document.getElementById('fileInput').click()">选择数据文件</label>
                        <button onclick="importData()" style="margin-top: 10px;">开始导入</button>
                        <div id="importStatus" style="margin-top: 10px; font-size: 12px;"></div>
                    </div>
                </div>
                
                <div class="tech-explanation" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                    <h4>🔧 服务器端数据持久化</h4>
                    <p>这个版本使用 <strong>Flask服务器</strong> 实现数据持久化：</p>
                    
                    <ul>
                        <li>数据存储在服务器的 <code>data/</code> 目录下的JSON文件中</li>
                        <li>使用 <code>classes.json</code> 存储班级数据</li>
                        <li>使用 <code>history.json</code> 存储历史记录</li>
                        <li>数据在服务器重启后依然保持</li>
                        <li>支持多设备同时访问相同的数据</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let classData = {};
        let freezeThreshold = 30;
        let recentHistory = [];
        let currentClassId = '';
        let activeClass = {};
        let timerInterval = null;
        
        // 从服务器加载数据
        async function loadData() {
            try {
                const response = await fetch('/api/data');
                if (!response.ok) throw new Error('网络响应不正常');
                
                const data = await response.json();
                classData = data.classData || {};
                freezeThreshold = data.freezeThreshold || 30;
                recentHistory = data.recentHistory || [];
                activeClass = data.activeClass || {}; // 这里只包含课堂计时器
                
                document.getElementById('freezeThreshold').value = freezeThreshold;
                document.getElementById('importStatus').innerHTML = '';
                updateDisplay();
                updateTimerDisplay();
                updateServerStatus(true);
                
                // 修复bug：只有在有活跃课程时才启动计时器
                if (activeClass.active && activeClass.classId) {
                    startTimer();
                } else {
                    // 确保没有活跃课程时，结束上课按钮是禁用的
                    document.getElementById('endClassBtn').disabled = true;
                }
                
                // 只有在核销面板更新时才检查奖励计时器，避免冲突
                // 不在这里调用 checkRewardTimer()
                
            } catch (error) {
                console.error('加载数据失败:', error);
                updateServerStatus(false);
                alert('加载数据失败，请检查服务器连接');
            }
        }
        
        // 更新计时器显示
        function updateTimerDisplay() {
            const timerDisplay = document.getElementById('timerDisplay');
            const sessionInfo = document.getElementById('sessionInfo');
            const startBtn = document.getElementById('startClassBtn');
            const endBtn = document.getElementById('endClassBtn');
            
            // 修复bug：只有在有活跃课程时才显示计时信息
            if (activeClass.active && activeClass.classId && classData[activeClass.classId]) {
                const minutes = Math.floor(activeClass.remaining / 60);
                const seconds = activeClass.remaining % 60;
                timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                
                sessionInfo.innerHTML = `
                    正在上课：${classData[activeClass.classId].name}<br>
                    开始时间：${activeClass.startTime}
                `;
                
                startBtn.disabled = true;
                endBtn.disabled = false;
            } else {
                // 没有活跃课程时，显示默认值
                timerDisplay.textContent = `${document.getElementById('classDuration').value || 40}:00`;
                sessionInfo.textContent = '当前没有进行中的课程';
                startBtn.disabled = !currentClassId; // 只有选择了班级才能开始上课
                endBtn.disabled = true;
            }
        }
        
        // 开始上课
        async function startClass() {
            if (!currentClassId) {
                alert('请先选择一个班级');
                return;
            }
            
            const duration = parseInt(document.getElementById('classDuration').value) || 40;
            
            try {
                const response = await fetch('/api/start-class', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId,
                        duration: duration
                    })
                });
                
                if (!response.ok) throw new Error('开始上课失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert('课程开始！系统将自动监测课堂纪律。');
                } else {
                    throw new Error(result.message || '开始上课失败');
                }
            } catch (error) {
                console.error('开始上课失败:', error);
                alert('开始上课失败，请检查服务器连接');
            }

            // 开始保持页面活跃
            keepPageAlive();
            
            // 每30秒触发一次保持活跃
            setInterval(keepPageAlive, 30000);
        }
        
        // 结束上课
        async function endClass() {
            // 修复bug：确保有活跃课程才能结束
            if (!activeClass.active || !activeClass.classId) {
                alert('没有正在进行的课程');
                return;
            }
            
            try {
                const response = await fetch('/api/end-class', {
                    method: 'POST'
                });
                
                if (!response.ok) throw new Error('结束上课失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 停止计时器
                    if (timerInterval) {
                        clearInterval(timerInterval);
                        timerInterval = null;
                    }
                    
                    // 重新加载数据
                    await loadData();
                    
                    if (result.hadDeduction) {
                        alert('课程结束！本节课有违纪记录，无协作表现奖励。');
                    } else {
                        alert('课程结束！本节课无违纪记录，已自动奖励协作表现分。');
                    }
                } else {
                    throw new Error(result.message || '结束上课失败');
                }
            } catch (error) {
                console.error('结束上课失败:', error);
                alert('结束上课失败，请检查服务器连接');
            }
        }
        
        // 启动计时器
        function startTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
            }
            
            timerInterval = setInterval(async () => {
                if (activeClass.active && activeClass.remaining > 0) {
                    activeClass.remaining--;
                    updateTimerDisplay();
                    
                    // 每10秒保存一次计时状态
                    if (activeClass.remaining % 10 === 0) {
                        await saveActiveClass();
                    }
                    
                    // 时间到自动结束课程
                    if (activeClass.remaining <= 0) {
                        await endClass();
                    }
                }
            }, 1000);
        }
        
        // 保存活跃课程状态
        async function saveActiveClass() {
            try {
                const response = await fetch('/api/data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classData: classData,
                        freezeThreshold: freezeThreshold,
                        recentHistory: recentHistory
                    })
                });
            } catch (error) {
                console.error('保存活跃课程状态失败:', error);
            }
        }
        
        // 计算自由探索时间
        function getFreeTime(score) {
            if (score >= 90) return 15;
            if (score >= 80) return 10;
            if (score >= 70) return 8;
            if (score >= 60) return 5;
            return 0;
        }
        
        // 获取最近4次课考勤状态
        function getAttendanceStatus(classId) {
            const sessions = [];
            for (let record of recentHistory) {
                if (record.classId === classId && record.type === 'class_session') {
                    sessions.push(record);
                    if (sessions.length >= 4) break;
                }
            }
            
            return sessions.reverse(); // 返回最近4次课，从最早到最近
        }
        
        // 更新班级卡片显示 - 只显示当前选中班级
        function updateClassGrid() {
            const classGrid = document.getElementById('classGrid');
            
            if (Object.keys(classData).length === 0) {
                classGrid.innerHTML = '<div class="empty-state">暂无班级数据，请先添加班级</div>';
                return;
            }
            
            classGrid.innerHTML = '';
            
            // 如果没有选中班级，显示提示
            if (!currentClassId || !classData[currentClassId]) {
                classGrid.innerHTML = `
                    <div class="empty-state">
                        <p>请先在上方选择班级查看详情</p>
                        <small>使用"选择班级"下拉菜单切换不同班级</small>
                    </div>
                `;
                return;
            }
            
            // 只显示当前选中的班级
            const classInfo = classData[currentClassId];
            const freeTime = getFreeTime(classInfo.score);
            const attendanceSessions = getAttendanceStatus(currentClassId);
            
            const classCard = document.createElement('div');
            classCard.className = `class-card ${getStatusClass(classInfo.score)}`;
            classCard.innerHTML = `
                <div class="class-header">
                    <div class="class-name">${classInfo.name}</div>
                    <div class="class-score">${classInfo.score}分</div>
                </div>
                
                <!-- 增强版进度条 -->
                <div class="progress-container">
                    <div class="progress-labels">
                        <span>暂停上课</span>
                        <span>自由探索</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${calculateProgressWidth(classInfo.score)}%">
                            <div class="progress-indicator">当前</div>
                        </div>
                        <div class="rule-markers">
                            <!-- 惩罚规则标记 -->
                            <div class="rule-marker" style="left: 20%;">
                                <div class="rule-label penalty">暂停2节课</div>
                            </div>
                            <div class="rule-marker" style="left: 30%;">
                                <div class="rule-label penalty">暂停1节课</div>
                            </div>
                            <div class="rule-marker" style="left: 40%;">
                                <div class="rule-label penalty">警告</div>
                            </div>
                            <!-- 奖励规则标记 -->
                            <div class="rule-marker" style="left: 60%;">
                                <div class="rule-label reward">5分钟</div>
                            </div>
                            <div class="rule-marker" style="left: 70%;">
                                <div class="rule-label reward">8分钟</div>
                            </div>
                            <div class="rule-marker" style="left: 80%;">
                                <div class="rule-label reward">10分钟</div>
                            </div>
                            <div class="rule-marker" style="left: 90%;">
                                <div class="rule-label reward">15分钟</div>
                            </div>
                        </div>
                    </div>
                    <div class="zone-labels">
                        <div class="zone-label zone-0">高风险区</div>
                        <div class="zone-label zone-1">警告区</div>
                        <div class="zone-label zone-2">观察区</div>
                        <div class="zone-label zone-3">奖励区</div>
                        <div class="zone-label zone-4">特权区</div>
                    </div>
                </div>
                
                <!-- 状态详情 -->
                <div class="status-details">
                    <div class="status-item">
                        <span class="status-icon">🎯</span>
                        <span>${freeTime > 0 ? `自由探索: ${freeTime}分钟` : '无自由探索权限'}</span>
                    </div>
                    <div class="status-item">
                        <span class="status-icon">⚠️</span>
                        <span>${getPenaltyStatus(classInfo.score)}</span>
                    </div>
                </div>
                
                <!-- 考勤状态 -->
                <div class="attendance-status">
                    <span>最近4次课:</span>
                    <div class="attendance-dots">
                        ${attendanceSessions.map(session => 
                            `<div class="attendance-dot ${session.hadDeduction ? 'inactive' : 'active'}"></div>`
                        ).join('')}
                        ${Array(4 - attendanceSessions.length).fill('<div class="attendance-dot"></div>').join('')}
                    </div>
                </div>
                
                <!-- 星星评级 -->
                <div class="stars">
                    ${'★'.repeat(getStarCount(classInfo.score))}${'☆'.repeat(5-getStarCount(classInfo.score))}
                </div>
            `;
            classGrid.appendChild(classCard);
        }
        
        // 更新核销面板
        async function updateClearancePanel() {
            if (!currentClassId || !classData[currentClassId]) {
                document.getElementById('rewardDesc').textContent = '请先选择一个班级';
                document.getElementById('penaltyDesc').textContent = '请先选择一个班级';
                document.getElementById('rewardCount').textContent = '0';
                document.getElementById('penaltyCount').textContent = '0';
                document.getElementById('resetClearanceBtn').disabled = true;
                return;
            }
            
            try {
                const response = await fetch(`/api/class-status/${currentClassId}`);
                if (!response.ok) {
                    const errorResult = await response.json();
                    throw new Error(errorResult.message || '获取状态失败');
                }
                
                const result = await response.json();
                if (result.status === 'success') {
                    const reward = result.reward;
                    const penalty = result.penalty;
                    
                    // 更新奖励显示
                    if (result.status === 'success') {
                        const reward = result.reward;
                        const penalty = result.penalty;
                        
                        // 更新奖励显示
                        if (reward.total > 0) {
                            document.getElementById('rewardDesc').textContent = 
                                `已使用 ${reward.used} 分钟，剩余 ${reward.remaining} 分钟`;
                            document.getElementById('rewardCount').textContent = reward.remaining;
                            document.getElementById('rewardMinutes').max = Math.min(15, reward.remaining);
                            document.getElementById('rewardMinutes').value = Math.min(5, reward.remaining);
                            document.querySelector('.clearance-btn.success').disabled = false;
                        } else {
                            document.getElementById('rewardDesc').textContent = '当前分数区间无自由探索时间';
                            document.getElementById('rewardCount').textContent = '0';
                            document.querySelector('.clearance-btn.success').disabled = true;
                        }
                    
                    // 更新惩罚显示
                    if (penalty.total > 0) {
                        document.getElementById('penaltyDesc').textContent = 
                            `${penalty.type}，已执行 ${penalty.used} 节，剩余 ${penalty.remaining} 节`;
                        document.getElementById('penaltyCount').textContent = penalty.remaining;
                        document.getElementById('penaltySessions').max = Math.min(3, penalty.remaining);
                        document.getElementById('penaltySessions').value = Math.min(1, penalty.remaining);
                    } else if (result.penalty.type !== "无惩罚") {
                        document.getElementById('penaltyDesc').textContent = 
                            `${penalty.type}（无需执行）`;
                        document.getElementById('penaltyCount').textContent = '0';
                    } else {
                        document.getElementById('penaltyDesc').textContent = '无待执行惩罚';
                        document.getElementById('penaltyCount').textContent = '0';
                    }
                    
                    // 更新重置按钮状态
                    const hasClearance = reward.remaining > 0 || penalty.remaining > 0;
                    document.getElementById('resetClearanceBtn').disabled = !hasClearance;
                    
                } else {
                    throw new Error(result.message || '获取状态失败');
                }
            }
            } catch (error) {
                console.error('更新核销面板失败:', error);
                document.getElementById('rewardDesc').textContent = '加载失败';
                document.getElementById('penaltyDesc').textContent = '加载失败';
            }
        }

        // 使用奖励时间
        async function useRewardTime() {
            if (!currentClassId) {
                alert('请先选择一个班级');
                return;
                    }
            
            const minutes = parseInt(document.getElementById('rewardMinutes').value) || 5;
            
            if (minutes <= 0) {
                alert('请输入有效的分钟数');
                return;
            }
            
            
            try {
                const response = await fetch('/api/use-reward', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId,
                        minutes: minutes
                    })
                });
                
                if (!response.ok) {
                    const errorResult = await response.json();
                    throw new Error(errorResult.message || '使用奖励失败');
                }
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert(`已使用 ${minutes} 分钟自由探索时间，剩余 ${result.remaining} 分钟`);
                } else {
                    throw new Error(result.message || '使用奖励失败');
                }
            } catch (error) {
                console.error('使用奖励失败:', error);
                alert(error.message || '使用奖励失败，请检查服务器连接');
            }
        }

        // 执行惩罚
        async function usePenaltySession() {
            if (!currentClassId) {
                alert('请先选择一个班级');
                return;
            }
            
            const sessions = parseInt(document.getElementById('penaltySessions').value) || 1;
            
            if (sessions <= 0) {
                alert('请输入有效的节数');
                return;
            }
            
            try {
                const response = await fetch('/api/use-penalty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId,
                        sessions: sessions
                    })
                });
                
                if (!response.ok) throw new Error('执行惩罚失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert(`已执行 ${sessions} 节停课惩罚，剩余 ${result.remaining} 节`);
                } else {
                    throw new Error(result.message || '执行惩罚失败');
                }
            } catch (error) {
                console.error('执行惩罚失败:', error);
                alert(`执行惩罚失败: ${error.message || '未知错误'}`);
            }
        }

        // 开始奖励倒计时
        async function startRewardTimer(minutes) {
            try {
                const response = await fetch('/api/start-reward-timer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId,
                        minutes: minutes
                    })
                });
                
                if (!response.ok) {
                    const errorResult = await response.json();
                    throw new Error(errorResult.message || '启动计时器失败');
                }
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 显示计时器控件
                    document.getElementById('rewardTimerControls').style.display = 'block';
                    
                    // 启动前端计时器
                
                    setTimeout(function() {
                        startRewardTimerDisplay(minutes);
                    }, 500);
                    
                    alert(`已开始 ${minutes} 分钟自由探索倒计时`);
                } else {
                    throw new Error(result.message || '启动计时器失败');
                }
            } catch (error) {
                console.error('启动计时器失败:', error);
                alert(error.message || '启动计时器失败，请检查服务器连接');
            }
        }

        // 开始前端奖励计时器显示
        function startRewardTimerDisplay(minutes) {
            let remaining = minutes * 60;
            const timerDisplay = document.getElementById('rewardTimerDisplay');
            
            // 清除可能存在的旧计时器
            if (window.rewardTimerInterval) {
                clearInterval(window.rewardTimerInterval);
            }
            
            window.rewardTimerInterval = setInterval(() => {
                if (remaining <= 0) {
                    clearInterval(window.rewardTimerInterval);
                    window.rewardTimerInterval = null;
                    timerDisplay.textContent = '时间到！';
                    
                    // 只在计时器自然结束时弹出提示
                    alert('自由探索时间已结束！');
                    document.getElementById('rewardTimerControls').style.display = 'none';
                    
                    // 通知后端计时器结束
                    notifyRewardTimerEnd();
                    return;
                }
                
                remaining--;
                const mins = Math.floor(remaining / 60);
                const secs = remaining % 60;
                timerDisplay.textContent = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }, 1000);
        }

        // 通知后端奖励计时器结束
        async function notifyRewardTimerEnd() {
            try {
                const response = await fetch('/api/end-reward-timer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                if (!response.ok) {
                    console.error('通知计时器结束失败');
                }
            } catch (error) {
                console.error('通知计时器结束失败:', error);
            }
        }

        // 停止奖励计时器
        function stopRewardTimer() {
            if (window.rewardTimerInterval) {
                clearInterval(window.rewardTimerInterval);
                window.rewardTimerInterval = null;
            }
            
            document.getElementById('rewardTimerControls').style.display = 'none';
            document.getElementById('rewardTimerDisplay').textContent = '00:00';
            alert('自由探索计时已停止');
        }

        // 检查奖励计时器状态
        async function checkRewardTimer() {
            try {
                const response = await fetch('/api/reward-timer-status');
                if (response.ok) {
                    const result = await response.json();
                    if (result.status === 'success' && result.active) {
                        // 有活动的计时器，恢复显示
                        document.getElementById('rewardTimerControls').style.display = 'block';
                        const mins = Math.floor(result.remaining / 60);
                        const secs = result.remaining % 60;
                        document.getElementById('rewardTimerDisplay').textContent = 
                            `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                        
                        // 启动前端计时器
                        startRewardTimerDisplay(result.remaining);
                    } else {
                        // 没有活动的计时器，确保控件隐藏
                        document.getElementById('rewardTimerControls').style.display = 'none';
                    }
                }
            } catch (error) {
                console.error('检查计时器状态失败:', error);
                // 出错时也隐藏控件，避免错误状态
                document.getElementById('rewardTimerControls').style.display = 'none';
            }
        }

        // 重置所有核销并恢复分数
        async function resetAllClearances() {
            if (!currentClassId || !classData[currentClassId]) {
                alert('请先选择一个班级');
                return;
            }
            
            const classInfo = classData[currentClassId];
            const initialScore = classInfo.initial_score || 40;
            
            if (!confirm(`确定要将 ${classInfo.name} 的分数重置为 ${initialScore} 分吗？这将清除所有奖励和惩罚记录。`)) {
                return;
            }
            
            try {
                // 直接重置分数到初始值
                classInfo.score = initialScore;
                classInfo.reward_used = 0;
                classInfo.penalty_used = 0;
                
                // 保存到服务器
                await saveData();
                
                // 重新加载数据
                await loadData();
                
                alert('分数已重置！');
            } catch (error) {
                console.error('重置分数失败:', error);
                alert('重置分数失败，请检查服务器连接');
            }
        }           
                
        // 获取惩罚等级
        function getPenaltyLevel(score) {
            if (score < 10) return 4; // 暂停3节课
            if (score < 20) return 3; // 暂停2节课
            if (score < 30) return 2; // 暂停1节课
            if (score < 40) return 1; // 警告
            return 0; // 无惩罚
        }
        
        // 核销奖励
        async function clearReward(classId, minutes) {
            if (!confirm(`确定要核销 ${classData[classId].name} 的 ${minutes} 分钟自由探索时间吗？`)) {
                return;
            }
            
            try {
                const response = await fetch('/api/clear-reward', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: classId,
                        minutes: minutes
                    })
                });
                
                if (!response.ok) throw new Error('核销失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert('奖励已核销！');
                } else {
                    throw new Error(result.message || '核销失败');
                }
            } catch (error) {
                console.error('核销奖励失败:', error);
                alert('核销奖励失败，请检查服务器连接');
            }
        }
        
        // 核销惩罚
        async function clearPenalty(classId, level) {
            let penaltyText = '';
            switch(level) {
                case 1: penaltyText = '警告通知班主任'; break;
                case 2: penaltyText = '暂停1节机房课'; break;
                case 3: penaltyText = '暂停2节机房课'; break;
                case 4: penaltyText = '暂停3节机房课'; break;
            }
            
            if (!confirm(`确定要核销 ${classData[classId].name} 的惩罚 "${penaltyText}" 吗？`)) {
                return;
            }
            
            try {
                const response = await fetch('/api/clear-penalty', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: classId,
                        level: level
                    })
                });
                
                if (!response.ok) throw new Error('核销失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert('惩罚已核销！');
                } else {
                    throw new Error(result.message || '核销失败');
                }
            } catch (error) {
                console.error('核销惩罚失败:', error);
                alert('核销惩罚失败，请检查服务器连接');
            }
        }
        
        // 全部核销并重置分数
        async function resetAllClearances() {
            if (!currentClassId || !classData[currentClassId]) {
                alert('请先选择一个班级');
                return;
            }
            
            const classInfo = classData[currentClassId];
            const freeTime = getFreeTime(classInfo.score);
            const penaltyLevel = getPenaltyLevel(classInfo.score);
            
            if (freeTime === 0 && penaltyLevel === 0) {
                alert('当前班级没有待核销的奖励或惩罚');
                return;
            }
            
            if (!confirm(`确定要核销 ${classInfo.name} 的所有奖励和惩罚，并将分数重置为初始值吗？`)) {
                return;
            }
            
            try {
                const response = await fetch('/api/reset-class', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId
                    })
                });
                
                if (!response.ok) throw new Error('重置失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据
                    await loadData();
                    alert('所有奖励和惩罚已核销，分数已重置！');
                } else {
                    throw new Error(result.message || '重置失败');
                }
            } catch (error) {
                console.error('重置班级失败:', error);
                alert('重置班级失败，请检查服务器连接');
            }
        }

        // 在updateDisplay函数中调用updateClearancePanel
        function updateDisplay() {
            updateClassSelectors();
            updateClassGrid();
            updateCurrentClassDisplay();
            updateClearancePanel(); // 添加这行
        }
        
        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签页
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            // 取消所有标签的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            // 激活选中的标签
            event.target.classList.add('active');
            
            // 如果切换到管理页面，更新班级列表
            if (tabName === 'manage') {
                updateClassList();
            } else if (tabName === 'history') {
                updateDetailedHistory();
            }
        }

        // 更新显示
        function updateDisplay() {
            updateClassSelectors();
            updateClassGrid();
            updateCurrentClassDisplay();
            updateClearancePanel();
        }

        // 更新班级选择器
        function updateClassSelectors() {
            const classSelect = document.getElementById('classSelect');
            const historyFilter = document.getElementById('historyClassFilter');
            
            // 清空选项（保留第一个提示选项）
            classSelect.innerHTML = '<option value="">-- 请选择班级 --</option>';
            historyFilter.innerHTML = '<option value="all">所有班级</option>';
            
            // 添加班级选项
            Object.keys(classData).forEach(classId => {
                const classInfo = classData[classId];
                const option = document.createElement('option');
                option.value = classId;
                option.textContent = `${classInfo.name} (${classInfo.score}分)`;
                classSelect.appendChild(option.cloneNode(true));
                historyFilter.appendChild(option);
            });
            
            // 如果当前选中的班级不存在，清空选择
            if (currentClassId && !classData[currentClassId]) {
                currentClassId = '';
                classSelect.value = '';
            } else if (currentClassId) {
                classSelect.value = currentClassId;
            }
        }

        // 更新当前班级显示
        function updateCurrentClassDisplay() {
            const display = document.getElementById('currentClassDisplay');
            if (currentClassId && classData[currentClassId]) {
                const classInfo = classData[currentClassId];
                display.textContent = `当前选中班级：${classInfo.name} (${classInfo.score}分)`;
            } else {
                display.textContent = '请先选择或创建一个班级';
            }
        }

        // 更新当前选中的班级
        function updateCurrentClass() {
            currentClassId = document.getElementById('classSelect').value;
            updateCurrentClassDisplay();
            updateClearancePanel();
            updateTimerDisplay(); // 修复bug：更新班级时也更新计时器显示
            updateClassGrid(); // 添加这行，更新班级卡片显示
        }

        // 快速记录
        async function quickRecord(points) {
            if (!currentClassId) {
                alert('请先选择一个班级');
                return;
            }
            
            const reasons = {
                '-1': '轻微违纪（随意走动、喧哗等）',
                '-2': '私自游戏/不听从指令',
                '-3': '严重违纪（损坏设备、顶撞老师等）',
                '1': '良好表现',
                '2': '优秀表现',
                '3': '突出贡献'
            };
            
            const reason = reasons[points.toString()] || '自定义记录';
            await recordPoints(points, reason);
        }

        // 自定义记录
        async function customRecord() {
            if (!currentClassId) {
                alert('请先选择一个班级');
                return;
            }
            
            const points = parseInt(document.getElementById('customPoints').value);
            const reason = document.getElementById('customReason').value;
            
            if (isNaN(points)) {
                alert('请输入有效的分数');
                return;
            }
            
            if (!reason) {
                alert('请输入记录原因');
                return;
            }
            
            await recordPoints(points, reason);
            
            // 清空输入框
            document.getElementById('customPoints').value = '';
            document.getElementById('customReason').value = '';
        }

        // 记录分数
        async function recordPoints(points, reason) {
            try {
                const response = await fetch('/api/record', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        classId: currentClassId,
                        points: points,
                        reason: reason
                    })
                });
                
                if (!response.ok) throw new Error('记录失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据以获取最新状态
                    await loadData();
                    
                    // 显示提示
                    const action = points > 0 ? '加分' : '扣分';
                    alert(`已为 ${classData[currentClassId].name} ${action}：${reason}（${points > 0 ? '+' : ''}${points}分）`);
                } else {
                    throw new Error(result.message || '记录失败');
                }
            } catch (error) {
                console.error('记录分数失败:', error);
                alert('记录分数失败，请检查服务器连接');
            }
        }

        // 添加班级
        async function addClass() {
            const name = document.getElementById('newClassName').value.trim();
            const score = parseInt(document.getElementById('newClassScore').value) || 55;
            
            if (!name) {
                alert('请输入班级名称');
                return;
            }
            
            try {
                const response = await fetch('/api/class', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: name,
                        score: score
                    })
                });
                
                if (!response.ok) throw new Error('添加失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据以获取最新状态
                    await loadData();
                    
                    // 清空输入框
                    document.getElementById('newClassName').value = '';
                    document.getElementById('newClassScore').value = '55';
                    
                    alert(`班级 "${name}" 添加成功！`);
                } else {
                    throw new Error(result.message || '添加失败');
                }
            } catch (error) {
                console.error('添加班级失败:', error);
                alert('添加班级失败，请检查服务器连接');
            }
        }

        // 更新班级列表（管理页面）
        function updateClassList() {
            const classList = document.getElementById('classList');
            
            if (Object.keys(classData).length === 0) {
                classList.innerHTML = '<div class="empty-state">暂无班级，请先添加班级</div>';
                return;
            }
            
            classList.innerHTML = '';
            
            Object.keys(classData).forEach(classId => {
                const classInfo = classData[classId];
                const classItem = document.createElement('div');
                classItem.className = 'class-item';
                classItem.innerHTML = `
                    <div>
                        <strong>${classInfo.name}</strong> 
                        <span style="color: #7f8c8d; font-size: 12px;">（创建于：${classInfo.created}）</span>
                    </div>
                    <div class="class-actions">
                        <button onclick="editClassScore('${classId}')">修改分数</button>
                        <button class="danger" onclick="deleteClass('${classId}')">删除</button>
                    </div>
                `;
                classList.appendChild(classItem);
            });
        }

        // 编辑班级分数
        async function editClassScore(classId) {
            const newScore = prompt(`请输入 ${classData[classId].name} 的新分数：`, classData[classId].score);
            if (newScore !== null && !isNaN(parseInt(newScore))) {
                // 计算分数差值
                const points = parseInt(newScore) - classData[classId].score;
                
                try {
                    const response = await fetch('/api/record', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            classId: classId,
                            points: points,
                            reason: '手动调整分数'
                        })
                    });
                    
                    if (!response.ok) throw new Error('更新失败');
                    
                    const result = await response.json();
                    if (result.status === 'success') {
                        // 重新加载数据以获取最新状态
                        await loadData();
                        alert('分数已更新！');
                    } else {
                        throw new Error(result.message || '更新失败');
                    }
                } catch (error) {
                    console.error('更新分数失败:', error);
                    alert('更新分数失败，请检查服务器连接');
                }
            }
        }

        // 删除班级
        async function deleteClass(classId) {
            if (!confirm(`确定要删除班级 "${classData[classId].name}" 吗？此操作不可撤销！`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/class/${classId}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) throw new Error('删除失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 重新加载数据以获取最新状态
                    await loadData();
                    alert('班级已删除！');
                } else {
                    throw new Error(result.message || '删除失败');
                }
            } catch (error) {
                console.error('删除班级失败:', error);
                alert('删除班级失败，请检查服务器连接');
            }
        }

        // 更新阈值
        async function updateThreshold() {
            freezeThreshold = parseInt(document.getElementById('freezeThreshold').value);
            await saveData();
            updateDisplay();
            alert(`特权冻结阈值已更新为：${freezeThreshold}分`);
        }

        // 更新详细历史记录
        function updateDetailedHistory() {
            const detailedHistory = document.getElementById('detailedHistory');
            const filter = document.getElementById('historyClassFilter').value;
            
            let filteredHistory = recentHistory;
            if (filter !== 'all') {
                filteredHistory = recentHistory.filter(record => record.classId === filter);
            }
            
            if (filteredHistory.length === 0) {
                detailedHistory.innerHTML = '<div class="empty-state">暂无历史记录</div>';
                return;
            }
            
            detailedHistory.innerHTML = filteredHistory.map(record => 
                `<div class="history-item ${record.points < 0 ? 'negative' : 'positive'}">
                    <div><strong>${record.time}</strong> ${record.className}</div>
                    <div>${record.reason}（${record.points > 0 ? '+' : ''}${record.points}分）</div>
                </div>`
            ).reverse().join('');
        }

        // 筛选历史记录
        function filterHistory() {
            updateDetailedHistory();
        }

        // 清除历史记录
        async function clearHistory() {
            if (confirm('确定要清除所有历史记录吗？此操作不可撤销！')) {
                recentHistory = [];
                await saveData();
                updateDetailedHistory();
                alert('历史记录已清除！');
            }
        }

        // 导出数据
        async function exportData() {
            try {
                const response = await fetch('/api/export');
                if (!response.ok) throw new Error('导出失败');
                
                // 创建下载链接
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `班级管理数据_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                alert('数据导出成功！');
            } catch (error) {
                console.error('导出数据失败:', error);
                alert('导出数据失败，请检查服务器连接');
            }
        }

        // 导入数据
        async function importData() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请先选择要导入的文件');
                return;
            }
            
            if (!file.name.endsWith('.json')) {
                alert('只支持JSON格式的文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/api/import', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) throw new Error('导入失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    document.getElementById('importStatus').innerHTML = `<span style="color: green;">${result.message}</span>`;
                    fileInput.value = '';
                    
                    // 重新加载数据
                    await loadData();
                } else {
                    throw new Error(result.message || '导入失败');
                }
            } catch (error) {
                console.error('导入数据失败:', error);
                document.getElementById('importStatus').innerHTML = `<span style="color: red;">导入失败：${error.message}</span>`;
            }
        }

        // 辅助函数
        function calculateProgressWidth(score) {
            return Math.max(0, Math.min(100, score));
        }

        function getStatusClass(score) {
            if (score >= 60) return 'safe';
            if (score >= 30) return 'warning';
            return 'danger';
        }

        function getPenaltyStatus(score) {
            if (score >= 50) return '无惩罚风险';
            if (score >= 40) return `再扣${50 - score}分将面临警告`;
            if (score >= 30) return `再扣${40 - score}分将暂停1节课`;
            if (score >= 20) return `再扣${30 - score}分将暂停2节课`;
            return `已面临暂停3节课风险，需立即改善`;
        }

        function getStarCount(score) {
            return Math.floor(score / 20);
        }

        function updateServerStatus(connected) {
            const statusElement = document.querySelector('.server-status');
            if (connected) {
                statusElement.textContent = '服务器连接正常';
                statusElement.style.background = '#27ae60';
            } else {
                statusElement.textContent = '服务器连接失败';
                statusElement.style.background = '#e74c3c';
            }
        }

        async function saveData() {
            try {
                const data = {
                    classData: classData,
                    freezeThreshold: freezeThreshold,
                    recentHistory: recentHistory
                };
                
                const response = await fetch('/api/data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                if (!response.ok) throw new Error('保存失败');
                
                const result = await response.json();
                if (result.status === 'success') {
                    updateServerStatus(true);
                } else {
                    throw new Error(result.message || '保存失败');
                }
            } catch (error) {
                console.error('保存数据失败:', error);
                updateServerStatus(false);
                alert('保存数据失败，请检查服务器连接');
            }
        }

        // 创建一个保持页面活跃的音频上下文
        let keepAliveAudioContext = null;

        function keepPageAlive() {
            try {
                // 创建一个极短的无声音频来保持页面活跃
                keepAliveAudioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = keepAliveAudioContext.createOscillator();
                oscillator.connect(keepAliveAudioContext.destination);
                oscillator.start();
                oscillator.stop(keepAliveAudioContext.currentTime + 0.001); // 立即停止
            } catch (e) {
                console.warn('无法创建 AudioContext:', e);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadData();

            // 初始化按钮状态
            const rewardButton = document.querySelector('.clearance-btn.success');
            if (rewardButton) {
                rewardButton.disabled = false;
            }
        });
    </script>
</body>
</html>